import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Socket;
import java.net.SocketException;

public class UdpEchoSever {
    private DatagramSocket socket = null;
    public UdpEchoSever(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("启动服务器！");
        //UDP不需要建立连接，直接从接受从客户端来的数据即可
        while(true){
           //1.读取客户端发来的数据
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(requestPacket);
            String request = new String(requestPacket.getData(),0,requestPacket.getLength(),"UTF-8");
           //2.根据请求计算相应
            String response = process(request);
           //3.根据响应写会到客户端
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(requestPacket);
            System.out.printf("[%s : %d] rep: %s, resp: %s\n",requestPacket.getAddress().toString(),requestPacket.getPort(),
                    request,response );
        }
    }
    private String process(String request) {
        return request;
    }
    public static void main(String[] args) throws IOException {
        UdpEchoSever sever = new UdpEchoSever(8080);
        sever.start();
    }
}


